@using Orchard.UI.Resources

@{
    var previewId = ViewContext.RouteData.Values["id"];
    Script.Require("jQuery").AtHead();
    Script.Include("js.cookie.js").AtHead();
}

<iframe id="iframe" style="display:none; position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden;z-index:999990;">
    @T("Your browser doesn't support iframes")
</iframe>

<iframe id="iframe2" style="display:none; position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden;z-index:999990;">
    @T("Your browser doesn't support iframes")
</iframe>

<div id="notConnectedWarning" class="message message-Error" role="alert" style="position:fixed; height:36px; top:10px;right:40px; display:none; z-index:999999;">
    <button type="button" id="close-connect-warning" class="close" aria-label="Close" style="position: relative; padding: 0 7px; border-radius: 7px; font-size:21px;">
        <span aria-hidden="true">&times;</span>
    </button>
    <span>@T("Preview Disconnected") </span>
</div>

<div id="renderPreviewUrl" style="display:none" data-value="@Url.Action("Render", "Preview", new { area = "Orchard.ContentPreview" })"></div>

<script type="text/javascript">
    ; (function ($) {
        $(function () {
        var renderPreviewUrl = $(document.getElementById('renderPreviewUrl')).data('value');
        var iframe = document.getElementById('iframe');
        var iframe2 = document.getElementById('iframe2');
        var previewEventTimer = null;
        var previewRenderTimer = null;

        $(function () {
            $(window).on('storage', function (ev) {
                if (ev.key.indexOf('contentpreview:not-connected:') !== -1) {
                    $(notConnectedWarning).show();
                }
                else if (ev.key.indexOf('contentpreview:') !== -1) {
                    if (ev.originalEvent.newValue != null) {
                        // Smooth event cascading
                        clearTimeout(previewEventTimer);
                        previewEventTimer = setTimeout(function () { renderPreview(ev.originalEvent.newValue); }, 150);
                        $(notConnectedWarning).hide();
                    }
                }
            });

            // override default behaviour of Bootstrap's. We only hide, not remove the alert.
            $('#close-connect-warning').on('click', function(){
                $('#notConnectedWarning').hide();
            });

            var preview = localStorage.getItem('contentpreview:@previewId');

            if (preview == null) {
                // notify the editor to render the preview
                localStorage.setItem('contentpreview:ready:@previewId', '');
                localStorage.removeItem('contentpreview:ready:@previewId');
            }
            else {
                renderPreview(preview);
            }
        });

        iframe.onload = function () {
            if (previewRendering) {
                this.style.display = 'block';
                $(this.contentWindow).scrollTop(scrollTop);

                if (iframe2 && iframe2.contentWindow) {
                    iframe2.style.display = 'none';
                    iframe2.contentWindow.document.open();
                    iframe2.contentWindow.document.write(previewRenderData);
                    iframe2.contentWindow.document.close();
                }
                previewRendering = false;
            }
        }

        var previewRendering;
        var previewRenderData;
        var scrollTop = 0;

        function renderPreview(value) {

            if (previewRendering) {
                // Defer the last rendering
                clearTimeout(previewRenderTimer);
                previewRenderTimer = setTimeout(function () { renderPreview(value); }, 100);
                return;
            }

            previewRendering = true;
            clearTimeout(previewRenderTimer);

            try {
                var formData = JSON.parse(value);
                if (!formData) {
                    previewRendering = false;
                    return;
                }

                $.post(renderPreviewUrl, formData)
                    .done(function (data) {
                        if (iframe && iframe.contentWindow && iframe2 && iframe2.contentWindow) {

                            // A full writing of the frame document causes the iframe to be re-loaded.
                            // So, better to update the scroll position on the related 'onload' event.
                            // Then, we use 2 frames to cancel the flicker that this deferring causes.

                            scrollTop = $(iframe.contentWindow).scrollTop();
                            iframe2.style.display = 'block';
                            $(iframe2.contentWindow).scrollTop(scrollTop);

                            iframe.style.display = 'none';
                            iframe.contentWindow.document.open();
                            iframe.contentWindow.document.write(data);
                            iframe.contentWindow.document.close();
                            previewRenderData = data;
                        }
                    })
                    .fail(function (data) {
                        previewRendering = false;
                    });
            }
            catch (e) {
                previewRendering = false;
                console.log('Error while previewing: ' + e);
            }
        }
        });
    })(jQuery);
</script>